import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:intl/intl.dart';
import 'package:family_app/src/features/finance/models/transaction_model.dart';
import 'package:family_app/src/features/finance/providers/finance_provider.dart';
import 'package:family_app/src/features/finance/screens/finance_detail_tab.dart';
import 'package:family_app/src/features/finance/screens/finance_category_tab.dart';
import 'package:family_app/src/features/finance/widgets/add_transaction_dialog.dart';
import 'package:family_app/src/features/finance/widgets/category_pie_chart.dart';
import 'package:family_app/src/features/finance/widgets/month_selector.dart';
import 'package:family_app/src/features/finance/widgets/summary_card.dart';
import 'package:family_app/src/features/finance/widgets/transaction_list_item.dart';
import 'package:family_app/src/theme/app_theme.dart';
import 'package:family_app/src/common/widgets/app_header.dart';

/// 记账本主界面
class FinanceScreen extends ConsumerStatefulWidget {
  const FinanceScreen({Key? key}) : super(key: key);

  @override
  ConsumerState<FinanceScreen> createState() => _FinanceScreenState();
}

class _FinanceScreenState extends ConsumerState<FinanceScreen>
    with TickerProviderStateMixin {
  late TabController _tabController;
  late AnimationController _fabAnimationController;
  late Animation<double> _fabScaleAnimation;
  late Animation<double> _fabPulseAnimation;

  @override
  void initState() {
    super.initState();
    // 初始化 TabController
    _tabController = TabController(length: 3, vsync: this);
    
    // 初始化悬浮按钮动画控制器
    _fabAnimationController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    );
    
    // 缩放动画
    _fabScaleAnimation = Tween<double>(
      begin: 0.8,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _fabAnimationController,
      curve: Curves.elasticOut,
    ));
    
    // 脉冲动画
    _fabPulseAnimation = Tween<double>(
      begin: 1.0,
      end: 1.1,
    ).animate(CurvedAnimation(
      parent: _fabAnimationController,
      curve: Curves.easeInOut,
    ));
    
    // 启动动画
    _fabAnimationController.repeat(reverse: true);
    
    // 刷新数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _refreshAllProviders();
    });
  }

  /// 刷新所有数据提供者
  void _refreshAllProviders() {
    // 刷新交易相关数据
    ref.invalidate(transactionsProvider);
    ref.invalidate(monthlyIncomeProvider);
    ref.invalidate(monthlyExpenseProvider);
    ref.invalidate(monthlyBalanceProvider);
    ref.invalidate(expenseCategoryStatsProvider);
    ref.invalidate(incomeCategoryStatsProvider);
    ref.invalidate(allCategoriesProvider);
    
    // 刷新年度账单数据
    ref.invalidate(yearlyBillListProvider);
  }

  @override
  void dispose() {
    // 释放 TabController
    _tabController.dispose();
    // 释放动画控制器
    _fabAnimationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final operationState = ref.watch(transactionOperationProvider);

    // 显示操作状态提示
    if (!operationState.isMessageShown) {
      _showOperationMessage(context, operationState);
    }

    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        title: Text(
          '记账本',
          style: TextStyle(
            fontSize: 20.sp,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
          onPressed: () => Navigator.of(context).pop(),
        ),
        centerTitle: true,
      ),
      body: Container(
        decoration: const BoxDecoration(
          gradient: AppTheme.backgroundGradient,
        ),
        child: SafeArea(
          child: TabBarView(
            controller: _tabController,
            children: [
              // 第一个 Tab - 详情
              const FinanceDetailTab(),
              
              // 第二个 Tab - 统计（当前记账本界面）
              _buildStatisticsTab(),
              
              // 第三个 Tab - 分类统计
              const FinanceCategoryTab()
            ],
          ),
        ),
      ),
      bottomNavigationBar: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20.r),
            topRight: Radius.circular(20.r),
          ),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 10,
              offset: const Offset(0, -2),
            ),
          ],
        ),
        child: TabBar(
          controller: _tabController,
          labelColor: AppTheme.primaryColor,
          unselectedLabelColor: Colors.grey.shade600,
          indicatorColor: AppTheme.primaryColor,
          indicatorWeight: 3,
          indicatorSize: TabBarIndicatorSize.label,
          labelStyle: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.w600,
          ),
          unselectedLabelStyle: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.w500,
          ),
          tabs: const [
            Tab(text: '详情'),
            Tab(text: '统计'),
            Tab(text: '分类统计'),
          ],
        ),
      ),
      floatingActionButton: AnimatedBuilder(
        animation: _fabAnimationController,
        builder: (context, child) {
          return Transform.scale(
            scale: _fabScaleAnimation.value * _fabPulseAnimation.value,
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(16.r),
                gradient: AppTheme.primaryGradient,
                boxShadow: [
                  BoxShadow(
                    color: AppTheme.primaryColor.withOpacity(0.4 * _fabPulseAnimation.value),
                    blurRadius: 12 * _fabPulseAnimation.value,
                    offset: const Offset(0, 6),
                    spreadRadius: 2 * (_fabPulseAnimation.value - 1),
                  ),
                ],
              ),
              child: FloatingActionButton(
                onPressed: () => _showAddTransactionDialog(context, ref),
                backgroundColor: Colors.transparent,
                elevation: 0,
                heroTag: "add_transaction",
                child: const Icon(
                  Icons.add_rounded,
                  color: Colors.white,
                  size: 28,
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  /// 构建统计 Tab（原记账本界面）
  Widget _buildStatisticsTab() {
    final selectedMonth = ref.watch(selectedMonthProvider);
    final transactionsAsync = ref.watch(transactionsProvider);
    final incomeAsync = ref.watch(monthlyIncomeProvider);
    final expenseAsync = ref.watch(monthlyExpenseProvider);
    final balanceAsync = ref.watch(monthlyBalanceProvider);

    return Column(
      children: [
        // 月份选择器
        Container(
          margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
          decoration: BoxDecoration(
            color: Colors.white.withOpacity(0.9),
            borderRadius: BorderRadius.circular(16.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                blurRadius: 10,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: MonthSelector(
            selectedMonth: selectedMonth,
            onMonthChanged: (month) {
              ref.read(selectedMonthProvider.notifier).state = month;
            },
          ),
        ),

        // 收支摘要
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          child: Row(
            children: [
              // 收入卡片
              Expanded(
                child: incomeAsync.when(
                  data: (income) => SummaryCard(
                    title: '收入',
                    amount: income.toDouble(),
                    icon: Icons.trending_up_rounded,
                    iconColor: Colors.green,
                    animationDelay: 100,
                  ),
                  loading: () => const SummaryCard(
                    title: '收入',
                    amount: 0,
                    icon: Icons.trending_up_rounded,
                    iconColor: Colors.green,
                    isLoading: true,
                    animationDelay: 100,
                  ),
                  error: (_, __) => const SummaryCard(
                    title: '收入',
                    amount: 0,
                    icon: Icons.trending_up_rounded,
                    iconColor: Colors.green,
                    hasError: true,
                    animationDelay: 100,
                  ),
                ),
              ),
              SizedBox(width: 8.w),
              // 支出卡片
              Expanded(
                child: expenseAsync.when(
                  data: (expense) => SummaryCard(
                    title: '支出',
                    amount: expense.toDouble(),
                    icon: Icons.trending_down_rounded,
                    iconColor: Colors.red,
                    animationDelay: 200,
                  ),
                  loading: () => const SummaryCard(
                    title: '支出',
                    amount: 0,
                    icon: Icons.trending_down_rounded,
                    iconColor: Colors.red,
                    isLoading: true,
                    animationDelay: 200,
                  ),
                  error: (_, __) => const SummaryCard(
                    title: '支出',
                    amount: 0,
                    icon: Icons.trending_down_rounded,
                    iconColor: Colors.red,
                    hasError: true,
                    animationDelay: 200,
                  ),
                ),
              ),
              SizedBox(width: 8.w),
              // 结余卡片
              Expanded(
                child: balanceAsync.when(
                  data: (balance) => SummaryCard(
                    title: '结余',
                    amount: balance.toDouble(),
                    icon: Icons.account_balance_wallet_rounded,
                    iconColor: AppTheme.primaryColor,
                    animationDelay: 300,
                  ),
                  loading: () => const SummaryCard(
                    title: '结余',
                    amount: 0,
                    icon: Icons.account_balance_wallet_rounded,
                    iconColor: Colors.blue,
                    isLoading: true,
                    animationDelay: 300,
                  ),
                  error: (_, __) => const SummaryCard(
                    title: '结余',
                    amount: 0,
                    icon: Icons.account_balance_wallet_rounded,
                    iconColor: Colors.blue,
                    hasError: true,
                    animationDelay: 300,
                  ),
                ),
              ),
            ],
          ),
        ),

        // 分类统计图表
        Container(
          height: 180.h,
          margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          decoration: BoxDecoration(
            color: Colors.white.withOpacity(0.9),
            borderRadius: BorderRadius.circular(20.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                blurRadius: 10,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Padding(
            padding: EdgeInsets.all(16.r),
            child: Row(
              children: [
                // 支出分类统计
                Expanded(
                  child: ref.watch(expenseCategoryStatsProvider).when(
                        data: (stats) => CategoryPieChart(
                          title: '支出分类',
                          categoryStats: stats,
                          type: TransactionType.expense,
                        ),
                        loading: () =>
                            const Center(child: CircularProgressIndicator()),
                        error: (_, __) => const Center(child: Text('加载失败')),
                      ),
                ),
                SizedBox(width: 16.w),
                // 收入分类统计
                Expanded(
                  child: ref.watch(incomeCategoryStatsProvider).when(
                        data: (stats) => CategoryPieChart(
                          title: '收入分类',
                          categoryStats: stats,
                          type: TransactionType.income,
                        ),
                        loading: () =>
                            const Center(child: CircularProgressIndicator()),
                        error: (_, __) => const Center(child: Text('加载失败')),
                      ),
                ),
              ],
            ),
          ),
        ),

        // 交易记录列表标题
        Container(
          margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
          decoration: BoxDecoration(
            color: Colors.white.withOpacity(0.9),
            borderRadius: BorderRadius.circular(16.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.05),
                blurRadius: 8,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Container(
                    padding: EdgeInsets.all(8.r),
                    decoration: BoxDecoration(
                      color: AppTheme.primaryColor.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(10.r),
                    ),
                    child: Icon(
                      Icons.receipt_long_rounded,
                      color: AppTheme.primaryColor,
                      size: 20.r,
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Text(
                    '交易记录',
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.bold,
                      color: AppTheme.textPrimaryColor,
                    ),
                  ),
                ],
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                decoration: BoxDecoration(
                  color: Colors.grey.shade100,
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Text(
                  DateFormat('yyyy年MM月').format(selectedMonth),
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: AppTheme.textSecondaryColor,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ],
          ),
        ),

        // 交易记录列表
        Expanded(
          child: Container(
            margin: EdgeInsets.only(top: 8.h),
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.95),
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(24.r),
                topRight: Radius.circular(24.r),
              ),
            ),
            child: transactionsAsync.when(
              data: (transactions) =>
                  _buildTransactionList(context, ref, transactions),
              loading: () => const Center(child: CircularProgressIndicator()),
              error: (error, stack) => Center(
                child:
                    Text('加载失败: $error', style: TextStyle(color: Colors.red)),
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 构建交易记录列表
  Widget _buildTransactionList(BuildContext context, WidgetRef ref,
      List<TransactionModel> transactions) {
    if (transactions.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.account_balance_wallet_outlined,
                size: 64.r, color: Colors.grey),
            SizedBox(height: 16.h),
            Text(
              '暂无交易记录',
              style: TextStyle(fontSize: 16.sp, color: Colors.grey),
            ),
            SizedBox(height: 16.h),
            ElevatedButton.icon(
              onPressed: () => _showAddTransactionDialog(context, ref),
              icon: const Icon(Icons.add),
              label: const Text('添加交易'),
              style: ElevatedButton.styleFrom(
                backgroundColor: AppTheme.primaryColor,
                foregroundColor: Colors.white,
              ),
            ),
          ],
        ),
      );
    }

    // 按日期降序排序
    final sortedTransactions = List<TransactionModel>.from(transactions)
      ..sort((a, b) => b.transactionDate.compareTo(a.transactionDate));

    return RefreshIndicator(
      onRefresh: () async {
        ref.invalidate(transactionsProvider);
      },
      child: ListView.builder(
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        itemCount: sortedTransactions.length,
        itemBuilder: (context, index) {
          final transaction = sortedTransactions[index];
          return TransactionListItem(
            transaction: transaction,
            onTap: () => _showEditTransactionDialog(context, ref, transaction),
            onDelete: () =>
                _showDeleteTransactionDialog(context, ref, transaction),
          );
        },
      ),
    );
  }

  /// 显示添加交易对话框
  void _showAddTransactionDialog(BuildContext context, WidgetRef ref) {
    showDialog(
      context: context,
      builder: (context) => AddTransactionDialog(
        onSubmit: (amount, type, category, description, date) async {
          Navigator.of(context).pop();
          await ref.read(transactionOperationProvider.notifier).addTransaction(
                amount: amount,
                type: type,
                category: category,
                description: description,
                transactionDate: date,
              );
        },
      ),
    );
  }

  /// 显示编辑交易对话框
  void _showEditTransactionDialog(
      BuildContext context, WidgetRef ref, TransactionModel transaction) {
    showDialog(
      context: context,
      builder: (context) => AddTransactionDialog(
        title: '编辑交易',
        submitButtonText: '保存',
        initialAmount: (transaction.amount / 100).round(),
        initialType: transaction.type,
        initialCategory: transaction.category,
        initialDescription: transaction.description,
        initialDate: transaction.transactionDate,
        onSubmit: (amount, type, category, description, date) async {
          Navigator.of(context).pop();
          await ref
              .read(transactionOperationProvider.notifier)
              .updateTransaction(
                id: transaction.id,
                amount: amount,
                type: type,
                category: category,
                description: description,
                transactionDate: date,
              );
        },
      ),
    );
  }

  /// 显示删除交易确认对话框
  void _showDeleteTransactionDialog(
      BuildContext context, WidgetRef ref, TransactionModel transaction) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除交易'),
        content: const Text('确定要删除这条交易记录吗？此操作不可恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.of(context).pop();
              await ref
                  .read(transactionOperationProvider.notifier)
                  .deleteTransaction(transaction.id);
            },
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  /// 显示操作状态提示
  void _showOperationMessage(
      BuildContext context, TransactionOperationState state) {
    if (state.isSuccess && state.message != null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(state.message!)),
        );
        // 标记消息已显示
        ref.read(transactionOperationProvider.notifier).markMessageShown();
      });
    } else if (!state.isSuccess && state.error != null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(state.error!),
            backgroundColor: Colors.red,
          ),
        );
        // 标记消息已显示
        ref.read(transactionOperationProvider.notifier).markMessageShown();
      });
    }
  }
}

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      home: const FinanceScreen(),
    ),
  );
}
